{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "42bcbfc9-e0bb-4748-b47b-eee74d12b50a",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - OpenAI Function\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "146126a2-ab3c-4b83-a332-0d5dabe92425",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "llm = ChatOpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1042d527-cae8-4b6d-a767-39014e2f6d68",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import tool\n",
    "\n",
    "@tool\n",
    "def get_word_length(word: str) -> int:\n",
    "    \"\"\"Returns the length of a word.\"\"\"\n",
    "    return len(word)\n",
    "\n",
    "tools = [get_word_length]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "54c7ba73-55fa-49cf-82cf-d310c1a8a0d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.schema import SystemMessage\n",
    "from langchain.agents import OpenAIFunctionsAgent\n",
    "\n",
    "system_message = SystemMessage(content=\"You are very powerful assistant, but bad at calculating lengths of words.\")\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ef0874c6-8076-4536-9533-bb9f69f450fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e7061c25-d090-4b52-a137-ba7545759241",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import AgentExecutor\n",
    "\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4f0ae154-5cb9-44cf-91d6-cc80308dcffc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `get_word_length` with `{'word': 'educa'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m5\u001b[0m\u001b[32;1m\u001b[1;3mThere are 5 letters in the word \"educa\".\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'There are 5 letters in the word \"educa\".'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.run(\"how many letters in the word educa?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2070d22f-c9d9-4346-b41d-e9beecb40625",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import MessagesPlaceholder\n",
    "\n",
    "MEMORY_KEY = \"chat_history\"\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(\n",
    "    system_message=system_message,\n",
    "    extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "849ebeac-aa8c-4ae8-b36c-c81a120147fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9af06fad-4f85-4411-b4f8-4fca7a45e09b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `get_word_length` with `{'word': 'educa'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m5\u001b[0m\u001b[32;1m\u001b[1;3mThere are 5 letters in the word \"educa\".\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mNo, \"educa\" is not a real word in English.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'No, \"educa\" is not a real word in English.'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)\n",
    "agent_executor.run(\"how many letters in the word educa?\")\n",
    "agent_executor.run(\"is that a real word?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2870681e-184f-4338-8cbb-3937e6bb33d0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
